import { app, shell, BrowserWindow, Tray, Menu, Notification } from 'electron'
import { join } from 'path'
import { optimizer, is } from '@electron-toolkit/utils'
import icon from '../../resources/icon.png?asset'
import { handler } from '../preload/ipc/handler'
// import { logger4 } from '../preload/ipc/log4'
import * as log from 'electron-log/main'
import * as path from "path";
import * as fs from "fs";
// import { updateTool } from './tools/updateTool'

let tray: Tray | null = null;
let quitting = false;
const iconPath = is.dev ? path.join(app.getAppPath(), 'resources', 'icon.png') : path.join(process.cwd(), 'resources', 'icon.png');
function createWindow(): void {
  // Create the browser window.
  const mainWindow = new BrowserWindow({
    title: '桌面应用6',
    width: 900,
    height: 670,
    show: false,
    autoHideMenuBar: true,
    ...(process.platform === 'linux' ? { icon } : {}),
    webPreferences: {
      preload: join(__dirname, '../preload/index.js'),
      sandbox: false
    }
  });
  //系统托盘
  //定义系统托盘的图标
  tray = new Tray(iconPath);
  //定义系统托盘的菜单
  const contextMenu = Menu.buildFromTemplate([
    {
      label: "打开主界面",
      click: () => {
        log.info("打开主界面");
        mainWindow.show();
      }
    }, {
      label: "退出",
      click: () => {
        log.info("退出app");
        quitting = true;
        app.quit();
      }
    }
  ]);

  tray.setContextMenu(contextMenu);
  tray.setToolTip('我的应用');
  tray.on("click", (_event) => {
    log.info("点击打开主界面");
    mainWindow.show();
  })
  //点击关闭的时候，隐藏窗口，而不是退出应用
  mainWindow.on("close", (event) => {
    if (!quitting) {
      log.info("隐藏窗口，而不是退出应用");
      event.preventDefault();
      mainWindow.hide();
    }
  })

  mainWindow.on('ready-to-show', () => {
    mainWindow.show();
    mainWindow.webContents.send("pong", ' I Pong on the main process');
  })

  mainWindow.webContents.setWindowOpenHandler((details) => {
    shell.openExternal(details.url)
    return { action: 'deny' }
  })

  // HMR for renderer base on electron-vite cli.
  // Load the remote URL for development or the local html file for production.
  if (is.dev && process.env['ELECTRON_RENDERER_URL']) {
    mainWindow.loadURL(process.env['ELECTRON_RENDERER_URL'])
  } else {
    mainWindow.loadFile(join(__dirname, '../renderer/index.html'))
  }
}

// This method will be called when Electron has finished
// initialization and is ready to create browser windows.
// Some APIs can only be used after this event occurs.
app.whenReady().then(() => {
  // Set app user model id for windows
  app.setAppUserModelId('我的应用');
  // const notify = new Notification({
  //   icon: iconPath,
  //   title: '桌面应用',
  //   body: '桌面应用启动成功'
  // });
  // notify.on("click", () => {
  //   log.info("点击通知");
  //   // close active
  //   //根据业务做出相对应的操作
  // })
  // notify.show();

  // Default open or close DevTools by F12 in development
  // and ignore CommandOrControl + R in production.
  // see https://github.com/alex8088/electron-toolkit/tree/master/packages/utils
  app.on('browser-window-created', (_, window) => {
    optimizer.watchWindowShortcuts(window)
  })

  log.transports.file.resolvePathFn = () => {
    const logDir = path.join(process.cwd(), 'logs');
    if (!fs.existsSync(logDir)) {
      fs.mkdirSync(logDir, { recursive: true });
    }
    return path.join(process.cwd(), 'logs', `main.log`);
  };
  log.initialize();

  handler.initializeHandlers();
  // logger4.initializeHandlers();
  // updateTool.checkUpdate();

  createWindow();
  app.on('activate', function () {
    // On macOS it's common to re-create a window in the app when the
    // dock icon is clicked and there are no other windows open.
    if (BrowserWindow.getAllWindows().length === 0) createWindow()
  })
})
// Quit when all windows are closed, except on macOS. There, it's common
// for applications and their menu bar to stay active until the user quits
// explicitly with Cmd + Q.
app.on('window-all-closed', () => {
  if (process.platform !== 'darwin') {
    // app.quit();
    log.info("window-all-closed 并没有退出应用");
  }
})

// In this file you can include the rest of your app's specific main process
// code. You can also put them in separate files and require them here.
